// 题库相关API接口
import axios from 'axios'
import type { Question, QuestionCategory, AnswerResult } from '../types/question'

// 从之前的定义中重新引入SearchQuestionParams接口
export interface SearchQuestionParams {
  keyword?: string
  type?: string
  difficulty?: string
  status?: string
  creatorId?: string | number
  categoryId?: string | number
  tagIds?: string[] | number[]
  chapterId?: string | number
  courseId?: string | number
  moduleId?: string | number
  groupId?: string | number
  isPublic?: boolean
  isOfficial?: boolean
  isHot?: boolean
  isRecommended?: boolean
  usedCountMin?: number
  usedCountMax?: number
  correctRateMin?: number
  correctRateMax?: number
  sortBy?: string
  sortOrder?: 'asc' | 'desc'
  startDate?: string
  endDate?: string
  page?: number
  pageSize?: number
}

// 临时定义QuestionPagination类型以匹配不同store中的使用
export interface QuestionPagination {
  data?: {
    items: Question[]
    currentPage: number
    pageSize: number
    total: number
    totalPages: number
  }
  items: Question[]
  currentPage: number
  pageSize: number
  total: number
  totalPages: number
}

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    console.error('API请求错误:', error)
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
    } else if (error.request) {
      console.error('请求失败，无响应:', error.request)
    } else {
      console.error('请求配置错误:', error.message)
    }
    return Promise.reject(error)
  }
)

// 获取题目分类
export const getQuestionCategories = async (): Promise<QuestionCategory[]> => {
  const response = await api.get('/questions/categories')
  return Array.isArray(response) ? response : []
}


// 获取题目详情
export const getQuestionDetail = async (questionId: number): Promise<Question> => {
  return await api.get(`/questions/${questionId}`)
}

// 提交答案
export const submitAnswer = async (questionId: number, answer: {
  optionId?: number
  optionIds?: number[]
  textAnswer?: string
}): Promise<AnswerResult> => {
  return await api.post(`/questions/${questionId}/answer`, answer)
}

// 收藏/取消收藏题目
export const favoriteQuestion = async (questionId: number): Promise<{ isFavorite: boolean }> => {
  return await api.post(`/questions/${questionId}/favorite`)
}

// 获取我的收藏题目
export const getFavoriteQuestions = async (params: {
  page?: number
  pageSize?: number
}): Promise<QuestionPagination> => {
  return await api.get('/questions/favorites', { params })
}

// 获取答题历史
export const getAnswerHistory = async (params: {
  page?: number
  pageSize?: number
  startDate?: string
  endDate?: string
}): Promise<{ list: { questionId: number, content: string, isCorrect: boolean, answerTime: string }[], total: number }> => {
  return await api.get('/questions/history', { params })
}

// 管理员创建题目
export const createQuestion = async (data: Omit<Question, 'id' | 'createdAt' | 'updatedAt'>): Promise<Question> => {
  return await api.post('/admin/questions', data)
}

// 管理员更新题目
export const updateQuestion = async (questionId: number, data: Partial<Question>): Promise<Question> => {
  return await api.put(`/admin/questions/${questionId}`, data)
}

// 管理员删除题目
export const deleteQuestion = async (questionId: number): Promise<void> => {
  return await api.delete(`/admin/questions/${questionId}`)
}

// 管理员批量导入题目
export const importQuestions = async (file: File): Promise<{ importedCount: number, failedCount: number }> => {
  const formData = new FormData()
  formData.append('file', file)
  return await api.post('/admin/questions/import', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
}

// 搜索题目
export const searchQuestions = async (params: SearchQuestionParams = {}): Promise<Question[]> => {
  try {
    console.log('🔍 调用搜索API，参数:', params)
    const response = await api.get('/questions/search', { params })
    console.log('🔍 搜索API响应:', response)
    
    // 处理分页响应 - 后端返回的是 Page<QuestionDto> 对象
    console.log('🔍 检查响应结构:', {
      hasResponse: !!response,
      hasData: !!(response && response.data),
      dataType: response?.data ? typeof response.data : 'undefined',
      isArray: Array.isArray(response?.data),
      hasContent: !!(response?.data?.content),
      contentIsArray: Array.isArray(response?.data?.content),
      contentLength: response?.data?.content?.length
    })
    
    // 检查响应结构
    if (response) {
      // 情况1: response直接包含content数组 (Spring Data Page格式)
      if ((response as any).content && Array.isArray((response as any).content)) {
        console.log('✅ 搜索成功，找到题目数量:', (response as any).content.length)
        return (response as any).content
      }
      // 情况2: response.data包含content数组 (Spring Data Page格式)
      else if (response.data && response.data.content && Array.isArray(response.data.content)) {
        console.log('✅ 搜索成功，找到题目数量:', response.data.content.length)
        return response.data.content
      }
      // 情况3: response.data是直接数组
      else if (response.data && Array.isArray(response.data)) {
        console.log('✅ 搜索成功，找到题目数量:', response.data.length)
        return response.data
      }
      // 情况4: response.data包含data数组
      else if (response.data && response.data.data && Array.isArray(response.data.data)) {
        console.log('✅ 搜索成功，找到题目数量:', response.data.data.length)
        return response.data.data
      }
      // 情况5: response本身是数组
      else if (Array.isArray(response)) {
        console.log('✅ 搜索成功，找到题目数量:', response.length)
        return response
      }
      else {
        console.warn('⚠️ 搜索响应格式异常:', response)
        console.log('🔍 响应数据结构:', Object.keys(response))
        console.log('🔍 响应数据内容:', response)
        return []
      }
    } else {
      console.warn('⚠️ 搜索响应为空:', response)
      return []
    }
  } catch (error: any) {
    console.error('❌ 搜索题目失败:', error)
    if (error.response) {
      console.error('响应状态:', error.response.status)
      console.error('响应数据:', error.response.data)
    } else if (error.request) {
      console.error('请求错误:', error.request)
    } else {
      console.error('错误信息:', error.message)
    }
    return []
  }
}

// 获取在线练习题目
export const getPracticeQuestions = async (params: {
  categoryId?: number
  difficulty?: number
  type?: string
  count: number
}): Promise<Question[]> => {
  try {
    const response = await api.get('/questions/practice', { params })
    return Array.isArray(response) ? response : []
  } catch (error) {
    console.error('获取练习题目失败:', error)
    return []
  }
}

// 提交练习答案
export const submitPracticeAnswers = async (data: {
  practiceId: string
  answers: Array<{
    questionId: number
    answer: any
    timeSpent: number
  }>
  timeSpent?: number
}): Promise<{
  score: number
  correctCount: number
  totalCount: number
  timeSpent: number
  analysis: Array<{
    questionId: number
    isCorrect: boolean
    correctAnswer: any
    userAnswer: any
    explanation: string
  }>
}> => {
  return await api.post('/questions/practice/submit', data)
}

// 获取练习历史
export const getPracticeHistory = async (params: {
  page?: number
  pageSize?: number
}): Promise<{
  list: Array<{
    id: string
    categoryName: string
    score: number
    correctCount: number
    totalCount: number
    timeSpent: number
    createdAt: string
  }>
  total: number
}> => {
  return await api.get('/questions/practice/history', { params })
}